<template>
    <el-dialog :model-value="props.visible" title="物流回单" width="35%" @close="handleClose">
        <div class="container">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="rules">
                <el-form-item label="发货方式" prop="deliveryMethod" align="right">
                    <el-select v-model="formData.deliveryMethod" placeholder="请选择">
                        <el-option v-for="item in props.sendTypeSalerOrder" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单号" prop="oddNumbers" align="right">
                    <el-input v-model="formData.oddNumbers" placeholder="请输入"></el-input>
                </el-form-item>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="运费" prop="freight" align="right">
                            <el-input type="number" v-model="formData.freight" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="送货费" prop="deliveryFee" align="right">
                            <el-input type="number" v-model="formData.deliveryFee" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="物流单" prop="fileUrl" align="right">
                    <el-upload
                        class="upload"
                        ref="uploadRef"
                        drag
                        :action="uploadImgUrl"
                        :headers="headers"
                        :limit="1"
                        :on-success="handleSuccess" 
                        :before-upload="beforeUpload"
                        :on-exceed="handleExceed"
                        :auto-upload="true"
                    >
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                            拖动文件 到这里 或 <em>点击上传</em>
                            <br />
                            png/jpg
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button  type="primary" @click="handleClickSubmit(formRef)" >确 定</el-button>
                <el-button @click="handleClose">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormInstance,UploadInstance, UploadProps,UploadRawFile } from 'element-plus';
import { globalHeaders } from "@/utils/request";
import {  genFileId } from 'element-plus';
import { addLogisticsApi } from '@/api/sj/saleManagement/orderDelivered'; 

const props = defineProps<{
    visible: boolean,
    orderDetails: any,
    sendTypeSalerOrder: any[]
}>();
const emits = defineEmits(['close','submit']);

const baseUrl = import.meta.env.VITE_APP_BASE_API;
const uploadImgUrl = ref(baseUrl + "/resource/oss/upload");
const headers = ref(globalHeaders);
const uploadRef = ref<UploadInstance>();
const fileTypes = import.meta.env.VITE_APP_FILE_TYPE.split(',');
const formRef = ref<FormInstance>();
const formData = ref({
    deliveryMethod: undefined,
    oddNumbers: undefined,
    freight: undefined,
    deliveryFee: undefined,
    remark: undefined,
    fileUrl: undefined
});

const checkFee = (rule: any,value: any,callback: any) => {
    if(!value){
        return callback(new Error('必填！'))
    }
    setTimeout(()=>{
        if(value < 0){
            callback(new Error('必须输入正数！'));
        }else{
            callback()
        }
    },500);
};

const rules = reactive({
    deliveryMethod: [
        {
            required: true,
            message: '请选择发货方式',
            trigger: 'change',
        }
    ],
    freight: [
        {validator: checkFee, trigger: 'blur'}
    ],
    deliveryFee: [
        {validator: checkFee, trigger: 'blur'}
    ],
    fileUrl: [
    { required: true, message: '未上传物流单凭证！', trigger: 'blur' },
    ]
})

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!fileTypes.includes(rawFile.type)) {
        ElMessage.error('图片格式与要求不符')
        return false
    } else if (rawFile.size / 1024 / 1024 > 5) {
        ElMessage.error('图片不可超过 5MB!')
        return false
    }
    return true
};

const handleSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // console.log(URL.createObjectURL(uploadFile.raw!),response);
    //@ts-ignore
    // formData.value.imageUrl = URL.createObjectURL(uploadFile.raw!);
    formData.value.fileUrl = response.data.url;
};

const handleExceed: UploadProps['onExceed'] = (files) => {
    uploadRef.value!.clearFiles()
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
};

const handleClickSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) =>{
        if(valid){
            const submitData = {
                ...formData.value,
                saleOrderId: props.orderDetails.id
            };
            const { code } = await addLogisticsApi(submitData);
            if(code == 200){
                emits('submit', true);
                handleClose();
            }else{
                emits('submit', false);
            };
        }else{
            console.log('error submit!',fields);
        }
    });
    
};

const handleClose = () => {
    formRef.value?.resetFields();
    uploadRef.value?.clearFiles();
    emits('close');
};
</script>

<style lang="scss" scoped>
.container{
    display: flex;
    justify-content: center;
    .el-form{
        width: 70%
    }
    .upload{
        width: 100%;
        ::v-deep(.el-upload-dragger){
            height: 95px;
            padding: 20px 10px;
            .el-icon{
                font-size: 20px;
                margin-bottom: 5px;
                line-height: 20px;
            }
            .el-upload__text{
                font-size: 13px;
                line-height: 13px;
            }
        }
    }
}
</style>